package huizhi.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.Charset;

/**
 * 客户端
 *
 * @author YuXD
 * @since 2023/12/25
 */
public class SocketClient3 {

    public static void main(String[] args) throws IOException {
        System.out.println("我是SocketClient");

        // 连接本机的8888端口
        Socket client = new Socket(InetAddress.getLocalHost(), 8888);
        // 从套接字获取字节输出流
        OutputStream outputStream = client.getOutputStream();
        outputStream.write("hello, Server！".getBytes(Charset.defaultCharset()));
        client.shutdownOutput();

        // 获取客户端输入字节流
        InputStream inputStream = client.getInputStream();
        // buffer
        byte[] buf = new byte[1024];
        // 读取到buf中的字节数
        int readLength;
        while (-1 != (readLength = inputStream.read(buf))) {
            System.out.println(new String(buf, 0, readLength));
        }

        outputStream.close();
        client.close();
    }

}
